<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <from action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </from>
    <!-- 搜索栏 -->

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- 搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- 联想建议 -->

    <!-- 历史记录 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
      @update-histories="searchHistories = $event"
    />
    <!-- 历史记录 -->
  </div>
</template>

<script>
import SearchHistory from "./components/search-history";
import SearchResult from "./components/search-result";
import SearchSuggestion from "./components/search-suggestion";
import { setItem, getItem } from "@/utils/storage";
// import { getSearchHistories } from "@/api/search";
import { mapState } from "vuex";
export default {
  name: "SearchIndex",
  components: { SearchHistory, SearchSuggestion, SearchResult },
  props: {},
  data() {
    return {
      searchText: "", //输入框内容
      isResultShow: false, //控制搜索结果的显示状态
      searchHistories: getItem("search-histories") || [], //搜索历史数据
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    //监听历史记录数据变化 存储到本地
    searchHistories() {
      setItem("search-histories", this.searchHistories);
    },
  },
  created() {
    this.loadSearchHistories();
  },
  mounted() {},
  methods: {
    onSearch(searchText) {
      //把输入框设置为你要搜索的文本
      this.searchText = searchText;

      //去除重复项
      const index = this.searchHistories.indexOf(searchText);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }

      //把最新的搜索历史放到顶部
      this.searchHistories.unshift(searchText);

      //用户登录，则把历史记录存储到线上
      //调用数据接口 后端会自动存储用户搜索历史记录
      //未登录，存储到本地
      // setItem("search-histories", this.searchHistories);
      //展示搜索结果
      this.isResultShow = true;
    },

    async loadSearchHistories() {
      //后端存储的历史记录【少】和本地的历史记录合并
      //无论是否登录 都存储到本地
      const searchHistories = getItem("search-histories") || [];
      // if (this.user) {
      //   const { data } = await getSearchHistories();
      //   searchHistories = [
      //     ...new Set([...searchHistories, ...data.data.keywords]),
      //   ];
      // }
      this.searchHistories = searchHistories;
    },
  },
};
</script>

<style scoped lang="less"></style>